﻿#include "pdfutil.h"
#include <QDebug>
#include <QPainter>

PdfUtil::PdfUtil(QObject *parent)
    : QObject(parent)
{
    qDebug() << "create PdfUtil";
    pPdf = std::make_unique<QPdfDocument>(this);
}

bool PdfUtil::open(QString filename, int width, int height)
{
    qDebug() << filename;
    QPdfDocument::Error e = pPdf->load(filename);
    qDebug() << "load result = " << e;
    qDebug() << pPdf->pageCount();
    QSizeF pageSize = pPdf->pagePointSize(0);
    qDebug() << pageSize.width() << " - " << pageSize.height();
    QImage image = pPdf->render(0, QSize(pageSize.width() * 2, pageSize.height() * 2));
    emit imgMsgChanged();
    this->pImageProvider->updateImage(image);

    QImage background(QSize(pageSize.width() * 2, pageSize.height() * 2), QImage::Format_ARGB32);
    background.fill(qRgba(255, 255, 255, 255)); // 白色填充
    QPainter painter(&background);
    // 在白色背景上绘制原始图像
    painter.drawImage(QPoint(0, 0), image);
    background.save("read.png", "PNG", 100);

    return true;
}

void PdfUtil::clipImg(double x, double y, int len)
{
    this->pImageProvider->clipImage(x, y, len);
}

void PdfUtil::setImageProvider(PdfImageProvider *p)
{
    this->pImageProvider = p;
}

void PdfUtil::setDataModel(DataModel *p)
{
    this->pDataModel = p;
}
